<?php
/**
 * LoveDiary.php
 * 文件描述
 * Created on 2020/9/1 15:29
 * Created by 刘小龙 595929049@qq.com
 */

namespace app\common\models;


use app\common\caches\DiaryCache;
use app\common\traits\BaseModelOptionTrait;
use think\Model;
use think\model\concern\SoftDelete;

class LoveDiary extends Model
{
    use BaseModelOptionTrait, SoftDelete;

    protected $table = 'xiangji_love_diaries';

    protected $autoWriteTimestamp = true;

    protected $defaultSoftDelete = 0;

    protected $deleteTime = 'delete_time';

    public static function onAfterRead($diary)
    {
        // 更新缓存
        DiaryCache::set($diary);
    }

    public static function onAfterInsert($diary)
    {
        // 插入缓存
        DiaryCache::set($diary);
        // 日记每日锁
        DiaryCache::setCreateDate($diary->user_id);
        // 刷新列表缓存
        DiaryCache::removeQueryData($diary->user_id);
    }

    public static function onAfterUpdate($diary)
    {
        // 更新缓存
        DiaryCache::set($diary);
        // 刷新列表缓存
        DiaryCache::removeQueryData($diary->user_id);
    }

    public static function onAfterDelete($diary)
    {
        // 移除缓存
        DiaryCache::del($diary);
        // 刷新列表缓存
        DiaryCache::removeQueryData($diary->user_id);
    }

    public function setContentAttr($value)
    {
        $preg='/<img.*?\/emoji\/(\d{1,3})\.gif.*?>/is';
        return preg_replace($preg, '[:bq.$1]', $value);
    }

    public function getContentAttr($value)
    {
        $preg='/\[:bq\.(\d{1,3})\]/is';
        return preg_replace($preg, '<img src=\'https://lovetime52.oss-cn-beijing.aliyuncs.com/emoji/$1.gif\'>', $value);
    }

    public function setImagesAttr($value)
    {
        return serialize($value);
    }
    public function getImagesAttr($value)
    {
        if (!$value) return [];
        return unserialize($value);
    }

    public function setLabelsAttr($value)
    {
        return serialize($value);
    }
    public function getLabelsAttr($value)
    {
        if (!$value) return [];
        return unserialize($value);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

}
